/* ----------------------------------------------------------------------------
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved.
 * Description: Tickless
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * --------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 * --------------------------------------------------------------------------- */
#include "los_tickless_pri.h"
#include "los_hwi.h"
#include "los_tick.ph"
#include "los_sortlink_pri.h"
#include "los_swtmr.ph"
#include "los_task.ph"
#include "nuclei_macro.h"

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */

static BOOL g_ticklessFlag = FALSE;
static BOOL g_tickIrqFlag[LOSCFG_KERNEL_CORE_NUM] = {FALSE};
static volatile UINT32 g_sleepTicks[LOSCFG_KERNEL_CORE_NUM] = {0};
UINT32 g_ticklessRUN = 0;

#define OS_GET_CYCLECOMPENSATE(cyclesPre,cyclesCur) (((cyclesPre) > (cyclesCur)) ? \
    ((OS_SYS_CLOCK / LOSCFG_BASE_CORE_TICK_PER_SECOND) - (cyclesCur)) : (((OS_SYS_CLOCK / LOSCFG_BASE_CORE_TICK_PER_SECOND) << 1) - (cyclesCur)))

LITE_OS_SEC_TEXT VOID LOS_TicklessEnable(VOID)
{
    g_ticklessFlag = TRUE;
    g_tickIrqFlag[ArchCurrCpuid()]=1;
}

LITE_OS_SEC_TEXT VOID LOS_TicklessDisable(VOID)
{
    g_ticklessFlag = FALSE;
    g_tickIrqFlag[ArchCurrCpuid()]=0;
}

LITE_OS_SEC_TEXT BOOL OsTicklessFlagGet(VOID)
{
    return g_ticklessFlag;
}

LITE_OS_SEC_TEXT BOOL OsTickIrqFlagGet(VOID)
{
    return g_tickIrqFlag[ArchCurrCpuid()];
}

LITE_OS_SEC_TEXT VOID OsTickIrqFlagSet(BOOL tickIrqFlag)
{
    g_tickIrqFlag[ArchCurrCpuid()] = tickIrqFlag;
}

LITE_OS_SEC_TEXT UINT32 OsTicklessSleepTickGet(VOID)
{
    return g_sleepTicks[ArchCurrCpuid()];
}

LITE_OS_SEC_TEXT VOID OsTicklessSleepTickSet(UINT32 sleeptick)
{
    g_sleepTicks[ArchCurrCpuid()] = sleeptick;
}

static INLINE UINT32 OsSleepTicksGet(VOID)
{
	
    UINT32 tskSortLinkTicks, swtmrSortLinkTicks, sleepTicks;
	///////////////////////////////////YHF CHANGE
    UINT32 intSave = LOS_IntLock();
//    LOS_SpinLock(&g_taskSpin);
//    tskSortLinkTicks = OsSortLinkGetNextExpireTime(&OsPercpuGet()->taskSortLink);
//    LOS_SpinUnlock(&g_taskSpin);
//    LOS_SpinLock(&g_swtmrSpin);
//    swtmrSortLinkTicks = OsSortLinkGetNextExpireTime(&OsPercpuGet()->swtmrSortLink);
//    LOS_SpinUnlock(&g_swtmrSpin);
//    sleepTicks = (tskSortLinkTicks < swtmrSortLinkTicks) ? tskSortLinkTicks : swtmrSortLinkTicks;
	
    LOS_IntRestore(intSave);
	///////////////////////////////////YHF CHANGE
    return sleepTicks;
}

LITE_OS_SEC_TEXT VOID OsSysTimeUpdate(UINT32 sleepTicks)
{
    UINT32 intSave;

    if (sleepTicks == 0) {
        return;
    }

    intSave = LOS_IntLock();
	//////////////////////////////////YHF CHANGE
//    g_tickCount[ArchCurrCpuid()] += (sleepTicks - 1);
//    LOS_SpinLock(&g_taskSpin);
//    OsSortLinkUpdateExpireTime(sleepTicks, &OsPercpuGet()->taskSortLink);
//    LOS_SpinUnlock(&g_taskSpin);
//    LOS_SpinLock(&g_swtmrSpin);
//    OsSortLinkUpdateExpireTime(sleepTicks, &OsPercpuGet()->swtmrSortLink);
//    LOS_SpinUnlock(&g_swtmrSpin);
    Tick_minus_num(sleepTicks);
	//////////////////////////////////YHF CHANGE
    LOS_IntRestore(intSave);
}

VOID OsTicklessUpdate(UINT32 irqnum)
{
    UINT32 cycles, ticks;
    UINT32 cyclesPertick;
    UINT32 sleepTicks;
    UINT32 intSave = LOS_IntLock();

    sleepTicks = OsTicklessSleepTickGet();
    if (sleepTicks == 0) {
        LOS_IntRestore(intSave);
        return;
    }

    cyclesPertick = OS_SYS_CLOCK / LOSCFG_BASE_CORE_TICK_PER_SECOND;
	//////////////////////////////YHF CHANGE
//    if (irqnum == OS_TICK_INT_NUM) {
//        OsSysTimeUpdate(sleepTicks);
//    } else {
//        cycles = HalClockGetTickTimerCycles();
//        cycles = (sleepTicks * cyclesPertick) - cycles;
//        ticks = cycles / cyclesPertick;
//        if (ticks < sleepTicks) {
//            cycles = cycles % cyclesPertick;
//            OsSysTimeUpdate(ticks + 1);
//            HalClockTickTimerReload(cyclesPertick - cycles);
//        } else {
//            /*
//             * If ticks is greater or equal to sleepTicks, it means the tick has already
//             * arrived, it should compensate with the sleepTicks just as that will be done
//             * in tick handler.
//             */
//            OsSysTimeUpdate(sleepTicks);
//        }
//    }
	//////////////////////////////YHF CHANGE
    OsTicklessSleepTickSet(0);

    LOS_IntRestore(intSave);
}

VOID OsTicklessStart(UINT32 Tick_Next)
{
    // UINT32 intSave;
    /*
     * The system has already started, the g_sysClock is non-zero and greater or equal to
     * LOSCFG_BASE_CORE_TICK_PER_SECOND (see OsTickInit). So the cyclesPerTick won't be zero.
     */
    UINT32 cyclesPerTick = OS_SYS_CLOCK / LOSCFG_BASE_CORE_TICK_PER_SECOND;
    UINT32 maxTicks = OS_NULL_INT / cyclesPerTick;
    UINT32 sleepTicks;
    UINT32 cycles, cyclesPre, cyclesCur, cycleCompensate;

    // intSave = LOS_IntLock();
    //////////////////////////YHF CHANGE
    // printf("\r\n2. NextSwitchTime is %d.\r\n",Tick_Next);

    if (Tick_Next >= maxTicks)
    {
        Tick_Next = maxTicks;
    }
    cycles = Tick_Next * cyclesPerTick;
    // *(UINT64 *)(TMR_CTRL_ADDR + TMR_MTIME) = 0;
    *(UINT64 *)(TMR_CTRL_ADDR + TMR_MTIMECMP) =(*(UINT64 *)(TMR_CTRL_ADDR + TMR_MTIME))+ cycles;
    // printf("\r\n2. Tickless cycles is %d.\r\n",cycles);
    // *(UINT64 *)(TMR_CTRL_ADDR + TMR_MTIMECMP) =OS_SYS_CLOCK / LOSCFG_BASE_CORE_TICK_PER_SECOND*10;

    //////////////////////////YHF CHANGE
    /*
     * The sleep tick may be changed afterwards, cause interrupt has been disabled, the sleep tick
     * may increase but cannot decrease. Thus there's no need to spin here.
     */
	 //////////////////////////YHF CHANGE
//    sleepTicks = OsSleepTicksGet();
//    cyclesPre = HalClockGetTickTimerCycles();
//
//    if (sleepTicks > 1) {
//        if (sleepTicks >= maxTicks) {
//            sleepTicks = maxTicks;
//        }
//        cycles = sleepTicks * cyclesPerTick;
//        cyclesCur = HalClockGetTickTimerCycles();
//        cycleCompensate = OS_GET_CYCLECOMPENSATE(cyclesPre, cyclesCur);
//        HalClockTickTimerReload(cycles - cycleCompensate);
//        OsTicklessSleepTickSet(sleepTicks);
//        LOS_IntRestore(intSave);
//
//        return;
//    }
	//////////////////////////YHF CHANGE
    // LOS_IntRestore(intSave);
    return;
}
VOID osTicklessHandler(VOID)
{
    UINT32 intSave;
    if (g_ticklessFlag)//g_ticklessFlag==1, run in tickless
    {
        
        intSave = LOS_IntLock();
        // g_tickIrqFlag[ArchCurrCpuid()]=1;
        // printf("OsTicklessStart!\r\n");
        g_sleepTicks[ArchCurrCpuid()]=osTaskNextSwitchTimeGet();
        if((g_tickIrqFlag[ArchCurrCpuid()])&&(g_sleepTicks[ArchCurrCpuid()]>10))
        {
            g_ticklessRUN++;
            // printf("\r\n2. Tickless entry.\r\n");
            OsTicklessStart(g_sleepTicks[ArchCurrCpuid()]); 
            //g_tickIrqFlag[ArchCurrCpuid()]=0;
        }
        LOS_IntRestore(intSave);
    }
    PMU_ToSleepMode(WFI_CMD);//sleep
    
}
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
